let productList;
$(function () {
        $.ajax({
            type: 'POST',
            url: '/userShow.action',
            contentType: 'application/json;charset=utf-8',
            success: function (result) {
                $("#workOrderMaker").val(result.loginId)
            }
        })
        $.ajax({
            type: 'POST',
            async: false,
            url: '/zjj/queryUndispatchedProductionSchedules.action',
            contentType: 'application/json;charset=utf-8',
            success: function (result) {
                productList = result.data;
                $.each(productList, function (i, v) {
                    let tr = $("<tr></tr>")
                        .append("<td><div class=\"form-check custom-checkbox mb-3 checkbox-success check-lg\"><input onclick='checkGenerateWorkOrder()' value='" + v.productId + "' type=\"checkbox\" class=\"form-check-input productClass\"></div></td>")
                        .append("<td>" + v.applyId + "</td>")
                        .append("<td>" + v.productId + "</td>")
                        .append("<td>" + v.productName + "</td>")
                        .append("<td>" + v.productDescribe + "</td>")
                        .append("<td>" + v.amount + "</td>")
                        .append("<td>" + v.mapplyCheckTime + "</td>")
                        .append("<td><button  value='" + v.id + "' data-toggle=\"modal\" data-target=\"#myModal\" class='btn btn-info' onclick='viewProductProfileInformation(this)'>查看</button></td>")

                    $("#tbodyCommodity").append(tr);
                })
                jQuery.getScript("../js/datatables.init.js")
            }
        })
    }
)

function viewProductProfileInformation(e) {
    $.each(productList, function (i, v) {
        if (v.id == $(e).val()) {
            $("#productId").val(v.productId)
            $("#type").val((v.type == 'Y001-1' ? '商品' : '物料'))
            $("#productName").val(v.productName)
            $("#factoryName").val(v.factoryName)
            $("#firstKingName").val(v.firstKingName)
            $("#secondKingName").val(v.secondKingName)
            $("#thirdKingName").val(v.thirdKingName)
            $("#productNick").val(v.productNick)
            $("#personalValue").val(v.personalValue)
            $("#productClass").val((v.productClass == 'D001-1' ? '高档' : v.productClass == 'D001-2' ? '中档' : '低档'))
            $("#personalUnit").val(v.personalUnit)
            $("#realCostPrice").val(v.realCostPrice)
            $("#listPrice").val(v.listPrice)
            $("#costPrice").val(v.costPrice)
            $("#registerTime").val(v.registerTime)
            $("#register").val(v.register)
            $("#checker").val(v.checker)
            $("#dfileCheckTime").val(v.dfileCheckTime)
            return;
        }
    })
}

function checkGenerateWorkOrder() {
    if ($(".productClass:checked").length > 0) {
        $("#generateWorkOrder").attr("disabled", false);
    } else {
        $("#generateWorkOrder").attr("disabled", true);
    }
}

$("#generateWorkOrder").click(function () {
    let productClass = $(".productClass:checked");
    let list = [];
    let quantity = 0;
    let productSectionInformation = new Array();
    $.each(productClass, function (i, v) {
        quantity += parseInt($(v).parent().parent().parent().children().eq(5).text())
        list[i] = $(v).val()
    })
    $.each(productList, function (i, v) {
        if (v.productId == list[0]) {
            productSectionInformation.push(productList[i])
        }
    })
    let temp = list[0];
    if (list.every(item => item === temp)) {
        $("#modRegisterTime").val(CurentTime())
        $("#modProductId").val(productSectionInformation[0].productId)
        $("#modRegister").val(productSectionInformation[0].register)
        $("#modProductName").val(productSectionInformation[0].productName)
        $("#modProductDescribe").val(productSectionInformation[0].productDescribe)
        $("#modAmount").val(quantity)
        $("#myModal1").modal(true);
    } else {
        commonUtil.message(2)
    }
})

let materialOperationList;
$("#through").click(function () {
    $.ajax({
        type: "POST",
        url: "/zjj/checkProcessMaterialIsItDone.action",
        dataType: "json",
        data: $(".productClass:checked").val(),
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            if (result.code == 5000) {
                myCommonUtil.message(1, "success", result.msg)
            } else {
                $("#tbody").html('')
                materialOperationList = result.data;
                $("#workOrderMaker1").val($("#workOrderMaker").val())
                $("#productNumber").val($("#modProductId").val())
                $("#productName1").val($("#modProductName").val())
                $("#quantity").val($("#modAmount").val())
                $("#description").val($("#modProductDescribe").val())
                $("#registerPerson1").val($("#modRegister").val())
                $("#checkInTime").val($("#modRegisterTime").val())
                $("#remark").val($("#auditOpinion").val())
                $.each(result.data, function (i, v) {
                    $("#designOrderNumber").val(v.parentId)
                    let tr = $("<tr></tr>")
                        .append("<td>" + (i + 1) + "</td>")
                        .append("<td>" + v.procedureName + "</td>")
                        .append("<td>" + v.procedureId + "</td>")
                        .append("<td>" + v.procedureDescribe + "</td>")
                        .append("<td>" + v.labourHourAmount + "</td>")
                        .append("<td>" + v.costPrice + "</td>")
                        .append("<td>" + v.subtotal + "</td>")
                        .append("<td><button  value='" + v.id + "'  class='btn btn-info' onclick='viewMaterial(this)'>查看物料</button></td>")
                    $("#tbody").append(tr)
                })
                $("#myModal2").modal(true);
            }
        }

    })
})

function viewMaterial(e) {
    let arr;
    $.each(materialOperationList, function (i, v) {
        if ($(e).val() == v.id) {
            arr = v.processMaterialDetails;
            return;
        }
    })
    $("#tbBody").html('')
    $("#processName").val($(e).parent().parent().children().eq(1).text())
    if (arr.length != 0) {
        $.each(arr, function (i, v) {
            let tr = $("<tr></tr>")
                .append("<td>" + (i + 1) + "</td>")
                .append("<td>" + v.productName + "</td>")
                .append("<td>" + v.productId + "</td>")
                .append("<td>" + v.productDescribe + "</td>")
                .append("<td>" + v.amount + "</td>")
                .append("<td>" + v.amountUnit + "</td>")
                .append("<td>" + v.costPrice + "</td>")
                .append("<td>" + v.subtotal + "</td>")
            $("#tbBody").append(tr)
            $("#myModal3").modal(true);
        })
    }else{
        myCommonUtil.message(1,"success","该工序没有物料")
    }

}

$("#submitAWorkOrder").click(fun => {
    let productionPlanNumber = [];
    $(".productClass:checked").each(function (i, v) {
        productionPlanNumber[i] = $(v).parent().parent().next().text();
    })
    let totalDesignMaterialCost = 0;
    let totalCostOfDesignManHours = 0;
    let processProductionQuantity = 0;
    let productionProcessTable = new Array();
    $.each(materialOperationList, function (i, v) {
        totalCostOfDesignManHours += v.subtotal;
        let temp = {
            detailsNumber: (i + 1),
            procedureId: v.procedureId,
            procedureName: v.procedureName,
            labourHourAmount: v.labourHourAmount,
            subtotal: v.subtotal,
            moduleSubtotal: 0,
            costPrice: v.costPrice,
            demandAmount: 0,
            procedureFinishTag: 'G004-0',
            productionMaterial: new Array()
        }
        $.each(v.processMaterialDetails, function (i, v) {
            let temp1 = {
                detailsNumber: v.detailsNumber,
                productId: v.productId,
                productName: v.productName,
                costPrice: v.costPrice,
                amount: v.amount,
                subtotal: v.subtotal
            }
            totalDesignMaterialCost += v.subtotal;
            processProductionQuantity += v.amount;
            temp.productionMaterial.push(temp1);
        })
        temp.moduleSubtotal = totalDesignMaterialCost;
        temp.demandAmount = processProductionQuantity;
        productionProcessTable.push(temp);
    })
    let productionSummary = {
        productId: $("#productNumber").val(),
        productName: $("#productName1").val(),
        amount: $("#quantity").val(),
        applyIdGroup: productionPlanNumber.join("|"),
        productDescribe: $("#description").val(),
        moduleCostPriceSum: totalDesignMaterialCost,
        labourCostPriceSum: totalCostOfDesignManHours,
        designer: $("#workOrderMaker1").val(),
        register: $("#registerPerson1").val(),
        registerTime: $("#checkInTime").val(),
        remark: $("#remark").val(),
        checkTag: 'S001-0',
        manufactureProcedureTag: 'S002-0',
        productionProcesses: new Array()
    };
    productionSummary.productionProcesses = productionProcessTable;
    $.ajax({
        type: 'POST',
        url: '/zjj/submitProductionDispatch.action',
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        data: JSON.stringify(productionSummary),
        success: function (result) {
            commonUtil.message(3);
            setTimeout(function () {
                window.location.reload();
            }, 2500)
        }
    })
})


var commonUtil = {
    /**
     * 弹出消息框
     * @param msg 消息内容
     * @param type 消息框类型（参考bootstrap的alert）
     */
    alert: function (msg, type) {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        // 创建bootstrap的alert元素
        if (msg == 1) {
            var divElement = $("<div style='width: 220px' class=\"alert alert-primary \"><svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"me-2\"><circle cx=\"12\" cy=\"12\" r=\"10\"></circle><path d=\"M8 14s1.5 2 4 2 4-2 4-2\"></path><line x1=\"9\" y1=\"9\" x2=\"9.01\" y2=\"9\"></line><line x1=\"15\" y1=\"9\" x2=\"15.01\" y2=\"9\"></line></svg><strong>OK!</strong> 添加产品成功.</div>\n")
        } else {
            var divElement = $("<div style='width: 320px' class=\"alert alert-light \">\n" +
                "    <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"me-2\"><polygon points=\"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\"></polygon><line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\"></line><line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\"></line></svg>\n" +
                "    <strong>Error!</strong> 只能选择相同的产品..\n" +
                "    </button>\n" +
                "</div>")
        }
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 180;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮
        var closeBtn = $('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"><i class="bi bi-x"></i></span></button>');
        $(divElement).append(closeBtn);
        // 消息框放入到页面中
        $('body').append(divElement);
        return divElement;
    },

    success: function () {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        var divElement = $("<div class=\"col-xl-3\">\n" +
            "<div class=\"alert alert-success left-icon-big alert-dismissible fade show\">\n" +
            "<div class=\"media\">\n" +
            "<div class=\"alert-left-icon-big\">\n" +
            "    <span><i class=\"mdi mdi-check-circle-outline\"></i></span>\n" +
            "</div>\n" +
            "<div class=\"media-body\">\n" +
            "    <h5 class=\"mt-1 mb-2\">submittedSuccessfully!</h5>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>")
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 180;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮

        // 消息框放入到页面中
        $('body'
        ).append(divElement);
        return divElement;
    },


    /**
     * 短暂显示后上浮消失的消息框
     * @param msg 消息内容
     * @param type 消息框类型
     */
    message: function (msg, type) {
        if (msg == 1 || msg == 2) {
            var divElement = commonUtil.alert(msg, type); // 生成Alert消息框
        } else {
            var divElement = commonUtil.success()
        }
        var isIn = false; // 鼠标是否在消息框中

        divElement.on({ // 在setTimeout执行之前先判定鼠标是否在消息框中
            mouseover: function () {
                isIn = true;
            },
            mouseout: function () {
                isIn = false;
            }
        });

        // 短暂延时后上浮消失
        setTimeout(function () {
            var IntervalMS = 20; // 每次上浮的间隔毫秒
            var floatSpace = 60; // 上浮的空间(px)
            var nowTop = divElement.offset().top; // 获取元素当前的top值
            var stopTop = nowTop - floatSpace;    // 上浮停止时的top值
            divElement.fadeOut(IntervalMS * floatSpace); // 设置元素淡出

            var upFloat = setInterval(function () { // 开始上浮
                if (nowTop >= stopTop) { // 判断当前消息框top是否还在可上升的范围内
                    divElement.css({"top": nowTop--}); // 消息框的top上升1px
                } else {
                    clearInterval(upFloat); // 关闭上浮
                    divElement.remove();    // 移除元素
                }
            }, IntervalMS);

            if (isIn) { // 如果鼠标在setTimeout之前已经放在的消息框中，则停止上浮
                clearInterval(upFloat);
                divElement.stop();
            }

            divElement.hover(function () { // 鼠标悬浮时停止上浮和淡出效果，过后恢复
                clearInterval(upFloat);
                divElement.stop();
            }, function () {
                divElement.fadeOut(IntervalMS * (nowTop - stopTop)); // 这里设置元素淡出的时间应该为：间隔毫秒*剩余可以上浮空间
                upFloat = setInterval(function () { // 继续上浮
                    if (nowTop >= stopTop) {
                        divElement.css({"top": nowTop--});
                    } else {
                        clearInterval(upFloat); // 关闭上浮
                        divElement.remove();    // 移除元素
                    }
                }, IntervalMS);
            });
        }, 1500);
    }
}

function CurentTime() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分

    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + "T";

    if (hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm;
    return (clock);
}


var myCommonUtil = {
    /**
     * 弹出消息框
     * @param msg 消息内容
     * @param type 消息框类型（参考bootstrap的alert）
     */
    alert: function (msg, type, v) {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        // 创建bootstrap的alert元素

        var divElement = $("<div style='width: 320px' class=\"alert alert-light \">\n" +
            "    <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"me-2\"><polygon points=\"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\"></polygon><line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\"></line><line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\"></line></svg>\n" +
            "    <strong>Error!</strong>" + v + "" +
            "    </button>\n" +
            "</div>")
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 180;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "z-index":9999,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮
        var closeBtn = $('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"><i class="bi bi-x"></i></span></button>');
        $(divElement).append(closeBtn);
        // 消息框放入到页面中
        $('body').append(divElement);
        return divElement;
    },

    success: function () {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        var divElement = $("<div class=\"col-xl-3\">\n" +
            "<div class=\"alert alert-success left-icon-big alert-dismissible fade show\">\n" +
            "<div class=\"media\">\n" +
            "<div class=\"alert-left-icon-big\">\n" +
            "    <span><i class=\"mdi mdi-check-circle-outline\"></i></span>\n" +
            "</div>\n" +
            "<div class=\"media-body\">\n" +
            "    <h5 class=\"mt-1 mb-2\">submittedSuccessfully!</h5>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>")
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 180;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮

        // 消息框放入到页面中
        $('body'
        ).append(divElement);
        return divElement;
    },


    /**
     * 短暂显示后上浮消失的消息框
     * @param msg 消息内容
     * @param type 消息框类型
     */
    message: function (msg, type, v) {
        if (msg == 1 || msg == 2) {
            var divElement = myCommonUtil.alert(msg, type, v); // 生成Alert消息框
        } else {
            var divElement = myCommonUtil.success()
        }
        var isIn = false; // 鼠标是否在消息框中

        divElement.on({ // 在setTimeout执行之前先判定鼠标是否在消息框中
            mouseover: function () {
                isIn = true;
            },
            mouseout: function () {
                isIn = false;
            }
        });

        // 短暂延时后上浮消失
        setTimeout(function () {
            var IntervalMS = 20; // 每次上浮的间隔毫秒
            var floatSpace = 60; // 上浮的空间(px)
            var nowTop = divElement.offset().top; // 获取元素当前的top值
            var stopTop = nowTop - floatSpace;    // 上浮停止时的top值
            divElement.fadeOut(IntervalMS * floatSpace); // 设置元素淡出

            var upFloat = setInterval(function () { // 开始上浮
                if (nowTop >= stopTop) { // 判断当前消息框top是否还在可上升的范围内
                    divElement.css({"top": nowTop--}); // 消息框的top上升1px
                } else {
                    clearInterval(upFloat); // 关闭上浮
                    divElement.remove();    // 移除元素
                }
            }, IntervalMS);

            if (isIn) { // 如果鼠标在setTimeout之前已经放在的消息框中，则停止上浮
                clearInterval(upFloat);
                divElement.stop();
            }

            divElement.hover(function () { // 鼠标悬浮时停止上浮和淡出效果，过后恢复
                clearInterval(upFloat);
                divElement.stop();
            }, function () {
                divElement.fadeOut(IntervalMS * (nowTop - stopTop)); // 这里设置元素淡出的时间应该为：间隔毫秒*剩余可以上浮空间
                upFloat = setInterval(function () { // 继续上浮
                    if (nowTop >= stopTop) {
                        divElement.css({"top": nowTop--});
                    } else {
                        clearInterval(upFloat); // 关闭上浮
                        divElement.remove();    // 移除元素
                    }
                }, IntervalMS);
            });
        }, 1500);
    }
}